{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-md-8 mx-auto">
        <div class="card">
            <div class="card-header bg-danger text-white">
                <h4><i class="fas fa-theater-masks"></i> 情景对话</h4>
                <small>模拟真实场景的英语对话练习</small>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label for="scenario-select" class="form-label">选择对话场景：</label>
                    <select class="form-select" id="scenario-select">
                        <option value="restaurant">餐厅点餐</option>
                        <option value="airport">机场问路</option>
                        <option value="hotel">酒店入住</option>
                        <option value="shopping">商场购物</option>
                        <option value="interview">工作面试</option>
                        <option value="daily">日常聊天</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <button id="start-btn" class="btn btn-success">
                        <i class="fas fa-play"></i> 开始对话
                    </button>
                    <button id="clear-btn" class="btn btn-outline-secondary" style="display: none;">
                        <i class="fas fa-redo"></i> 重新开始
                    </button>
                </div>
                
                <div id="chat-container" style="height: 300px; overflow-y: auto; border: 1px solid #ddd; padding: 15px; margin-bottom: 15px; border-radius: 10px; background: #f8f9fa; display: none;">
                </div>
                
                <div id="input-container" style="display: none;">
                    <div class="input-group">
                        <input type="text" id="user-input" class="form-control" placeholder="输入你的英语回应...">
                        <button id="send-btn" class="btn btn-danger">
                            <i class="fas fa-paper-plane"></i> 发送
                        </button>
                    </div>
                    <small class="text-muted mt-2">💡 提示：用英语回应AI老师的对话</small>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const scenarioSelect = document.getElementById('scenario-select');
    const startBtn = document.getElementById('start-btn');
    const clearBtn = document.getElementById('clear-btn');
    const chatContainer = document.getElementById('chat-container');
    const inputContainer = document.getElementById('input-container');
    const userInput = document.getElementById('user-input');
    const sendBtn = document.getElementById('send-btn');

    let currentScenario = '';

    function addMessage(content, isUser = false) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `alert ${isUser ? 'alert-warning' : 'alert-info'}`;
        messageDiv.style.marginBottom = '10px';
        messageDiv.innerHTML = isUser ? 
            `<strong>你:</strong> ${content}` : 
            `<strong>AI老师:</strong> ${content.replace(/\n/g, '<br>')}`;
        
        chatContainer.appendChild(messageDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    async function startConversation() {
        currentScenario = scenarioSelect.value;
        
        startBtn.disabled = true;
        startBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 启动中...';
        
        try {
            const response = await fetch('/conversation', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ 
                    scenario: currentScenario,
                    message: ''  // 空消息表示开始新对话
                })
            });
            
            const data = await response.json();
            
            // 显示对话界面
            chatContainer.style.display = 'block';
            inputContainer.style.display = 'block';
            clearBtn.style.display = 'inline-block';
            
            // 添加AI的初始消息
            addMessage(data.response);
            
        } catch (error) {
            alert('启动对话失败，请重试。');
        } finally {
            startBtn.disabled = false;
            startBtn.innerHTML = '<i class="fas fa-play"></i> 开始对话';
            userInput.focus();
        }
    }

    async function sendMessage() {
        const message = userInput.value.trim();
        if (!message) return;
        
        addMessage(message, true);
        userInput.value = '';
        sendBtn.disabled = true;
        sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 发送中...';
        
        try {
            const response = await fetch('/conversation', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ 
                    scenario: currentScenario,
                    message: message
                })
            });
            
            const data = await response.json();
            addMessage(data.response);
            
        } catch (error) {
            addMessage('抱歉，发送消息时出现错误。请检查网络连接。');
        } finally {
            sendBtn.disabled = false;
            sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i> 发送';
            userInput.focus();
        }
    }

    async function clearConversation() {
        if (confirm('确定要重新开始对话吗？当前对话历史将被清空。')) {
            try {
                const response = await fetch(`/clear_conversation/${currentScenario}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                // 清空界面
                chatContainer.innerHTML = '';
                chatContainer.style.display = 'none';
                inputContainer.style.display = 'none';
                clearBtn.style.display = 'none';
                
                alert('对话已重置');
            } catch (error) {
                alert('重置对话失败');
            }
        }
    }

    // 事件监听
    startBtn.addEventListener('click', startConversation);
    sendBtn.addEventListener('click', sendMessage);
    clearBtn.addEventListener('click', clearConversation);
    
    userInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
});
</script>
{% endblock %}